package bit.springblogdemo.common.intercepter;

import bit.springblogdemo.common.advice.constant.Constants;
import bit.springblogdemo.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static bit.springblogdemo.common.advice.constant.Constants.USER_TOKEN_HEADER_KEY;

@Component
@Slf4j
public class LoginIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader(USER_TOKEN_HEADER_KEY);
        log.info("从header中获取token:"+userToken);
        if(userToken == null) {
            response.setStatus(401);
            return false;
        }

        Claims claims= JwtUtils.parseToken(userToken);
        if(claims == null) {
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
